const BASE_URL = "/api";
// const BASE_URL="/api";//基础请求路径 http://172.16.123.66:8888
function http({ url, method = "get", data = {}, headers = {} }) {
  if (!url) {
    return;
  }
  //封装token
  headers["token"] = sessionStorage.getItem("token");

  //判断method 为get 还是post
  if (method.toLocaleUpperCase() === "GET") {
    //get请求    a=1&b=2
    return fetch(BASE_URL + url + "?" + toStr(data), {
      method,
      headers,
    }).then((res) => {
      return res.json();
    });
  } else if (method.toLocaleUpperCase() === "POST") {
    headers["Content-Type"] = "application/json";
    return fetch(BASE_URL + url, {
      method,
      body: JSON.stringify(data),
      headers,
    }).then((res) => {
      return res.json();
    });
  }
}

//专门用于将 json 对象转成  a=1&b=2 格式的函数
function toStr(json) {
  let str = "";
  for (let key in json) {
    str += `${key}=${json[key]}&`;
  }
  return str.slice(0, str.length - 1);
}

export default http;
